using B.S.Database.Domain.Entity;
using B.S.Database.ErrorCode;
using B.S.Database.Interface.Interface;
using B.S.Database.Write.Api.Application.Commands.Image;
using MediatR;
using System.Reflection;

namespace B.S.Database.Write.Api.Application.CommandHandler.Image
{
    public class PictureListCommandHandler : IRequestHandler<PictureListCommands, Apiresult<object>>
    {
        private readonly IBaseResotity<Picture_Information> _pictureRepository;
        private readonly ILogger<PictureListCommandHandler> _logger;

        public PictureListCommandHandler(
            IBaseResotity<Picture_Information> pictureRepository,
            ILogger<PictureListCommandHandler> logger)
        {
            _pictureRepository = pictureRepository;
            _logger = logger;
        }

        public async Task<Apiresult<object>> Handle(PictureListCommands request, CancellationToken cancellationToken)
        {
            var result = new Apiresult<object>();

            try
            {
                // 验证请求
                if (request.TraceabilityId <= 0)
                {
                    result.Code = ApiEnums.失败;
                    result.Message = "溯源ID不能为空";
                    return result;
                }

                if (string.IsNullOrEmpty(request.ImageType))
                {
                    result.Code = ApiEnums.失败;
                    result.Message = "图片类型不能为空";
                    return result;
                }

                // 验证图片类型
                if (!IsValidImageType(request.ImageType))
                {
                    result.Code = ApiEnums.失败;
                    result.Message = "无效的图片类型";
                    return result;
                }

                // 查找数据库记录
                var existingPicture = _pictureRepository.GetAll().FirstOrDefault(x => x.TraceabilityId == request.TraceabilityId);
                if (existingPicture == null)
                {
                    result.Code = ApiEnums.失败;
                    result.Message = "未找到对应的图片记录";
                    return result;
                }

                // 获取当前字段的图片URL
                var currentUrls = GetPropertyValue(existingPicture, request.ImageType);
                if (string.IsNullOrEmpty(currentUrls))
                {
                    result.Code = ApiEnums.成功;
                    result.Message = "该字段没有图片数据";
                    result.Data = new
                    {
                        TraceabilityId = request.TraceabilityId,
                        ImageType = request.ImageType,
                        Images = new List<object>(),
                        TotalCount = 0
                    };
                    return result;
                }

                var urlList = currentUrls.Split(request.Separator, StringSplitOptions.RemoveEmptyEntries).ToList();
                var imageList = new List<object>();

                for (int i = 0; i < urlList.Count; i++)
                {
                    imageList.Add(new
                    {
                        Index = i,
                        Url = urlList[i],
                        FileName = ExtractFileName(urlList[i])
                    });
                }

                result.Code = ApiEnums.成功;
                result.Message = $"成功获取 {imageList.Count} 张图片";
                result.Data = new
                {
                    TraceabilityId = request.TraceabilityId,
                    ImageType = request.ImageType,
                    Images = imageList,
                    TotalCount = imageList.Count
                };
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "获取图片列表过程中发生错误");
                result.Code = ApiEnums.失败;
                result.Message = $"获取图片列表失败: {ex.Message}";
            }

            return result;
        }

        /// <summary>
        /// 从URL中提取文件名
        /// </summary>
        private string ExtractFileName(string url)
        {
            try
            {
                if (string.IsNullOrEmpty(url))
                    return string.Empty;

                var uri = new Uri(url);
                return Path.GetFileName(uri.LocalPath);
            }
            catch
            {
                return string.Empty;
            }
        }

        /// <summary>
        /// 验证图片类型是否有效
        /// </summary>
        private bool IsValidImageType(string imageType)
        {
            var validTypes = new[]
            {
                "Inspection_Repor",
                "Livestock_Certification",
                "Certification_Documents",
                "Food_Safety",
                "Raw_Material",
                "Auxiliary_Materials",
                "Additive_Materials",
                "Packaging_Materials",
                "Enterprise_Image"
            };

            return validTypes.Contains(imageType);
        }

        /// <summary>
        /// 获取属性值
        /// </summary>
        private string GetPropertyValue(Picture_Information picture, string propertyName)
        {
            var property = typeof(Picture_Information).GetProperty(propertyName);
            return property?.GetValue(picture)?.ToString() ?? "";
        }
    }
} 